//
//  KLBookEntityDAO.m
//  KLBookStore
//
//  Created by apple on 2017/10/15.
//  Copyright © 2017年 NetEaseExam. All rights reserved.
//

#import "KLBookEntityDAO.h"

@implementation KLBookEntityDAO

+ (long long)insertModel:(KLBookEntity *)bookEntity withDataBase:(FMDatabase *)db {
    
    BOOL success = [db executeUpdate:@"insert into 'TB_BOOK_ENTITY'  (doubanId, isbn10, isbn13, title, doubanUrl, image, publisher, pubdate, price, summary, author_intro) values (?,?,?,?,?,?,?,?,?,?,?)",@(bookEntity.doubanId),bookEntity.isbn10,bookEntity.isbn13,bookEntity.title,bookEntity.doubanUrl,bookEntity.image,bookEntity.publisher,bookEntity.pubdate,bookEntity.price,bookEntity.summary,bookEntity.author_intro];
    
    if (success) {
        return [db lastInsertRowId];
    } else {
        return 0;
    }
}

+ (KLBookEntity *)queryModelById:(long long)localId withDataBase:(FMDatabase *)db {
    FMResultSet *resultSet = [db executeQuery:@"select * from 'TB_BOOK_ENTITY' where id = ?", @(localId)];
    if ([resultSet next]) {
        KLBookEntity *entity = [[KLBookEntity alloc] initWithFMResultSet:resultSet];
        [resultSet close];
        return entity;
    }
    return nil;
}

+ (KLBookEntity *)queryModelByDoubanId:(long long)doubanId withDataBase:(FMDatabase *)db {
    FMResultSet *resultSet = [db executeQuery:@"select * from 'TB_BOOK_ENTITY' where doubanId = ?", @(doubanId)];
    if ([resultSet next]) {
        KLBookEntity *entity = [[KLBookEntity alloc] initWithFMResultSet:resultSet];
        [resultSet close];
        return entity;
    }
    return nil;
}

+ (BOOL)deleteModelWithId:(long long)localId withDataBase:(FMDatabase *)db {
    BOOL success = [db executeUpdate:@"delete from 'TB_BOOK_ENTITY' where id = ?",@(localId)];
    return success;
}

+ (BOOL)deleteModelWithDoubanId:(long long)doubanId withDataBase:(FMDatabase *)db {
    BOOL success = [db executeUpdate:@"delete from 'TB_BOOK_ENTITY' where doubanId = ?",@(doubanId)];
    return success;
}

+ (NSArray<KLBookEntity *> *)queryAllModelsWithDataBase:(FMDatabase *)db {
    NSMutableArray *results = [@[] mutableCopy];
    FMResultSet *resultSet = [db executeQuery:@"select * from 'TB_BOOK_ENTITY'"];
    while ([resultSet next]) {
        KLBookEntity *entity = [[KLBookEntity alloc] initWithFMResultSet:resultSet];
        [results addObject:entity];
    }
    [resultSet close];
    return results;
}

+ (NSArray<KLBookEntity *> *)queryModelsWithDataBase:(FMDatabase *)db offset:(long long)offset pageSize:(NSUInteger)size {
    NSMutableArray *results = [@[] mutableCopy];
    FMResultSet *resultSet = [db executeQuery:@"select * from 'TB_BOOK_ENTITY' order by id desc limit ?, ?", @(offset), @(size)];
    while ([resultSet next]) {
        KLBookEntity *entity = [[KLBookEntity alloc] initWithFMResultSet:resultSet];
        [results addObject:entity];
    }
    [resultSet close];
    return results;
}

@end
